package com.sinosoft.msf.base.supplier.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;

import com.sinosoft.msf.base.supplier.pojo.*;
import com.sinosoft.msf.base.supplier.props.IpAddressEnum;
import com.sinosoft.msf.base.supplier.props.ProjectStateEnum;
import com.sinosoft.msf.base.supplier.service.CommonBizService;
import com.sinosoft.msf.base.supplier.service.CompanyUserRoleService;
import com.sinosoft.msf.base.supplier.service.ProjectService;
import com.sinosoft.msf.base.supplier.service.SupSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@RestController
@RequestMapping("/project")
public class ProjectController {
    private static final Logger log = LoggerFactory.getLogger(ProjectController.class);
    @Autowired
    ProjectService projectService;
    @Autowired
    CommonBizService bizService;
    @Autowired
    SupSendService sendService;
    @Autowired
    CompanyUserRoleService userRoleService;
    private OptVo curentOpt() {
        return bizService.queryCureUserInfo();
    }

    @PostMapping(value = "/query", name = "项目列表查询")
    public RestEntity queryProject(@RequestBody ProjectQueryReqPojo reqPojo) {
        OptVo optVo = curentOpt();
        ProjectQueryReqPojo.ParamData paramData = reqPojo.getParamData();
        paramData.setAuditUserId(optVo.getUserId());
        if (StrUtil.isNotEmpty(paramData.getCreatedDate())) {
            String[] split = paramData.getCreatedDate().split(",");
            if(split.length==2){
                paramData.setCreatedDateStart(split[0]);
                paramData.setCreatedDateEnd(split[1]);
            }
        }
        Set<String> roles = userRoleService.queryRole(optVo);
        String status = paramData.getStatus();
        if (ProjectStateEnum.lgd.name().equals(status)) {
            if(roles.contains("legal2")){
                paramData.setStatus(ProjectStateEnum.lgd2.name());
            }else if(roles.contains("legal")){
                paramData.setStatus(ProjectStateEnum.lgd.name());
            }else{
                paramData.setStatus("NN");
            }
        }else{
            if (!roles.contains("admin")) {
                paramData.setUserId(optVo.getUserId());
            }
        }

        Page<ProjectInfoPojo> projectInfoPojos = projectService.queryProject(reqPojo);
        return RestEntity.data(projectInfoPojos);
    }

    @PostMapping(value = "/stagSave", name = "暂存项目")
    public RestEntity stagSave(@RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getCompanys())) {
            return RestEntity.error("请选择供应商");
        }
        OptVo optVo = curentOpt();
        String s = projectService.stagSave(projectInfoPojo, optVo);
        return RestEntity.success(s);
    }
    @PostMapping(value = "/save", name = "保存项目")
    public RestEntity saveProject(@RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getCompanys())) {
            return RestEntity.error("请选择供应商");
        }
        OptVo optVo = curentOpt();
        CodeNameVo s = projectService.saveProject(projectInfoPojo,optVo);
        return RestEntity.data(s);
    }

    @PostMapping(value = "/edit", name = "保存项目")
    public RestEntity editProject(@RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getCompanys())) {
            return RestEntity.error("请选择供应商");
        }
        OptVo optVo = curentOpt();
        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择需要编辑的项目");
        projectInfoPojo.setProReport(null);
        projectService.clearReport(projectInfoPojo.getId());
        CodeNameVo s = projectService.editProject(projectInfoPojo,optVo);
        return RestEntity.data(s);
    }

    @PostMapping(value = "/detail", name = "项目详情")
    public RestEntity detailProject(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "项目ID不可为空");
        ProjectInfoPojo detail = projectService.detail(projectInfoPojo.getId(),true);
        return RestEntity.data(detail);
    }

    @PostMapping(value = "/del", name = "删除项目")
    public RestEntity delProject(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择需要删除的项目");
        projectService.delProject(projectInfoPojo.getId());
        return RestEntity.success();
    }

    @PostMapping(value = "/hasAllPrice", name = "是否全部上传报价单")
    public RestEntity hasAllPrice(HttpServletRequest request, @RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "项目ID不可为空");
        long count = projectService.hasAllPrice(projectInfoPojo.getId());
        return RestEntity.data(count);
    }
    @PostMapping(value = "/queryPriceList", name = "查询报价单")
    public RestEntity queryPriceList(HttpServletRequest request, @RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "项目ID不可为空");
        Validator.validateNotEmpty(projectInfoPojo.getSupId(), "供应商ID不可为空");
        String s = bizService.queryPriceFile(projectInfoPojo.getId(), projectInfoPojo.getSupId(),true);
        return RestEntity.data(s);
    }
    @PostMapping(value = "/savePriceList", name = "保存报价单")
    public RestEntity savePriceList(HttpServletRequest request, @RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getFiles())) {
            return RestEntity.error("请上传报价单");
        }
        if (projectInfoPojo.getFiles().size() > 1) {
            return RestEntity.error("只可上传一个报价单");
        }
        if (StrUtil.isEmpty(projectInfoPojo.getFiles().get(0).getUrl())) {
            return RestEntity.error("请上传报价单");
        }
        String clientIP = ServletUtil.getClientIP(request);
        log.info("获取到的客户端IP:{}", clientIP);
        projectService.savePriceList(projectInfoPojo, clientIP);
        return RestEntity.success();
    }

    @PostMapping(value = "/savePriceTemplete", name = "保存报价单模板")
    public RestEntity savePriceTemplete(@RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getFiles())) {
            return RestEntity.error("请上传报价单");
        }
        if (projectInfoPojo.getFiles().size() > 1) {
            return RestEntity.error("只可上传一个报价单模板");
        }
        String userId = "";
        projectService.savePriceTemplete(projectInfoPojo, userId);
        return RestEntity.success();
    }

//    @PostMapping(value = "/valiePrice", name = "验证项目是否全部上传报价单")
//    public RestEntity valiePrice(@RequestBody ProjectInfoPojo projectInfoPojo) {
//        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择项目");
//        projectService.valiePrice(projectInfoPojo.getId());
//        return RestEntity.success();
//    }

    @PostMapping(value = "/sendPriceEmail", name = "发送供应商上传报价单邮件")
    public RestEntity sendBillEmail(@RequestBody ProjectInfoPojo projectInfoPojo) {
        if (CollUtil.isEmpty(projectInfoPojo.getCompanys())) {
            return RestEntity.error("请选择供应商");
        }
        projectService.sendPriceEmail(projectInfoPojo);
        return RestEntity.success("已经发送邮件");
    }

    @PostMapping(value = "/reAudit", name = "提交复审")
    public RestEntity reAudit(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择项目");
//        Validator.validateNotEmpty(projectInfoPojo.getAuditRemark(), "请录入审核内容");
        OptVo optVo = curentOpt();
        projectService.reAudit(projectInfoPojo, optVo);
        return RestEntity.success();
    }

    @PostMapping(value = "/selectSup", name = "选择供应商")
    public RestEntity selectSup(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择项目");
        List<String> selectedIds = projectInfoPojo.getSelectedIds();
        if (CollUtil.isEmpty(selectedIds)) {
            return RestEntity.error("请选择中标供应商");
        }
        OptVo optVo = curentOpt();
        projectService.selectSup(projectInfoPojo, optVo);
        return RestEntity.success();
    }

    @PostMapping(value = "/saveAudit", name = "保存合规审核")
    public RestEntity saveAudit(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getAuditResult(), "请选择审核结论");
        if("n".equals(projectInfoPojo.getAuditResult())){
            Validator.validateNotEmpty(projectInfoPojo.getAuditRemark(), "请录入审核意见");
        }
        OptVo optVo = curentOpt();
        return RestEntity.data(projectService.saveAudit(projectInfoPojo, optVo));
    }

    @PostMapping(value = "/toSign", name = "发起签报")
    public RestEntity toSign(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "请选择项目");
        OptVo optVo = curentOpt();
        String url = projectService.toSign(projectInfoPojo, optVo);
        return RestEntity.data(url);
    }

    @PostMapping(value = "/valiComInfo", name = "验证项目的供应商信息")
    public RestEntity valiComInfo(@RequestBody ValiComInfoPojo comInfoPojo) {
        Validator.validateNotEmpty(comInfoPojo.getId(), "缺少项目信息");
        Validator.validateNotEmpty(comInfoPojo.getPhone(), "缺少手机号信息");
        Validator.validateNotEmpty(comInfoPojo.getValiCode(), "缺少验证码信息");
        sendService.valiPhoneCode(comInfoPojo.getPhone(), comInfoPojo.getValiCode(),"");
        String comId = projectService.valiPhone(comInfoPojo);
        return RestEntity.data(comId);
    }

    @PostMapping(value = "/projectBaseInfo", name = "获取项目基本信息")
    public RestEntity projectBaseInfo(@RequestBody ProjectInfoPojo projectInfoPojo) {
        Validator.validateNotEmpty(projectInfoPojo.getId(), "项目ID不可为空");
        Validator.validateNotNull(projectInfoPojo.getValiInfo(), "请验证公司信息");
        return RestEntity.data(projectService.projectBaseInfo(projectInfoPojo));
    }

    @PostMapping(value = "/detail/pdf", name = "生成项目的供应商pdf报告")
    public RestEntity createProjectCompanyPDF(@RequestBody JSONObject jsonObject) {
        Validator.validateNotEmpty(jsonObject.getString("id"), "项目id不可为空");
        return RestEntity.data(projectService.createProjectCompanyPDF(jsonObject.getString("id")));
    }
    @PostMapping(value = "/sync/signState", name = "同步签批状态")
    public RestEntity syncSignState(@RequestBody SyncSignStateVo signStateVo) {
        String serNo = Optional.ofNullable(signStateVo)
                .map(SyncSignStateVo::getBody)
                .map(SyncSignStateVo.BodyDTO::getProjectSeriaNo).orElse("");
         String state = Optional.ofNullable(signStateVo)
                .map(SyncSignStateVo::getBody)
                .map(SyncSignStateVo.BodyDTO::getState).orElse("");
        Validator.validateNotEmpty(serNo, "项目id不可为空");
        Validator.validateNotEmpty(state, "签批状态不可为空");
        projectService.syncSignState(serNo, state);
        return RestEntity.success("同步成功");
    }
}
